﻿using UnityEngine;
using System.Collections;

public class Megaman : MonoBehaviour {
	private bool onGround = false;
	private float currentJumpDelta = 0;
	private float maxGravVelocity = -0.5f;
	private bool stillHoldingJump = false;
	private bool facingRight;
	private const float JUMP_DECREMENT = 0.01f;
	private const float JUMP_START_VELOCITY = 0.25f;
	public float walkSpeed = 0.05f;
	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		//Update mega man's position
		Vector3 newMegaPosition = transform.position;
		//listen for movement keys
		if (Input.GetKey (KeyCode.RightArrow)) {
			newMegaPosition.x += walkSpeed;
			facingRight = true;
		} else if (Input.GetKey (KeyCode.LeftArrow)) {
			newMegaPosition.x -= walkSpeed;
			facingRight = false;
		}
		if (Input.GetKey (KeyCode.Z)) {
			if (onGround && !stillHoldingJump) {
				stillHoldingJump = true;	//makes it so that you don't just hold the button and keep jumping
				currentJumpDelta = JUMP_START_VELOCITY;
				onGround = false;
			}
		} else {
			if (onGround) {
				//we have let go of Z on the ground, so we can update the boolean
				stillHoldingJump = false;
			}
		}
		
		//if not on the ground, fall
		if (!onGround) {
			//update the jumping velocity
			if (currentJumpDelta > maxGravVelocity) {
				currentJumpDelta -= JUMP_DECREMENT;
			}
			newMegaPosition.y += currentJumpDelta;	//if currentJumpDelta is negative this means we are falling
			
		}
		//Finally, use the cached position to update the transform's actual position.
		transform.position = newMegaPosition;
	}
	
	void OnTriggerEnter(Collider other) {
		onGround = true;
		currentJumpDelta = 0;
		//calculate the y position to compensate for falling through the ground
		float boxTop = other.bounds.max.y;	//top of the box we collided with
		BoxCollider myBox = transform.gameObject.collider as BoxCollider;
		Vector3 newPosition = transform.position;
		newPosition.y = boxTop + myBox.bounds.extents.y;
		transform.position = newPosition;
	}
	
	void OnTriggerExit(Collider other) {
		onGround = false;
	}
}
